<!-- 前台领料明细 -->
<template>
  <div>
    <!-- 表单 -->
    <FormPanel ref="form" :cols="3" :list="list" :isSubmitBtn="false"></FormPanel>
    <FilterTable
      ref="table"
      :columns="columns"
      columnsRef="partPartOutboundRepairMaterialsComponentsReception"
      :height="'auto'"
      :isExportExcel="true"
      exportFileName="前台领料查询.xlsx"
      :dataSource="dataSource"
      :onSyncTableData="syncDataChange"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="onRowSelectChange"
    >
      <template slot="moreActions">
        <span v-if="isShow" @click="() => deleteHandle()">删除数据</span>
      </template>
      <template slot="controls" slot-scope="props">
        <el-button v-if="isShow" size="small" type="primary" @click="showAddWxll">新增</el-button>
      </template>
    </FilterTable>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="$emit('cancel')">关 闭</el-button>
      <AjaxButton v-if="isShow" type="primary" :click="saveDialog">保 存</AjaxButton>
    </div>
    <!-- 新增 -->
    <Drawer :visible.sync="isShowAddWxll" title="前台领料新增">
      <!-- <AddPanelRec :roNo="roNo" :partIsHave="partIsHave" @addRow="addRow" @confirm="confirmAddWxll" @cancel="isShowAddWxll = false"></AddPanelRec> -->
    </Drawer>
  </div>
</template>

<script>
import { queryMaintainPicking, getSfqfSelect, saveRepairFront, delFrontPartInfo } from '@/api/part/partOutbound/repairMaterials/index.js';
import { getDealerUser } from '@/api/part/partInventory/partInventory/index.js';
import { state, mutations } from '../store';
import { dictionary } from '@/utils/dictMixin';
import { sleep, arrayObjDeWeight, isAuthorized } from '@/utils';
// import AddPanelRec from './AddPanelRec';
import util from '../common/util';
import { getUserId } from '@/assets/js/auth';
import { getLingLiaoRenSelect } from '@/api/part/partOutbound/repairMaterials/dict.js';

export default {
  name: 'wxll_wxxmmx',
  components: {
    // AddPanelRec
  },
  mixins: [dictionary],
  props: {
    roNo: String,
    tax: {
      type: String,
      default: '0'
    },
    isShow: {
      type: Boolean,
      default: true
    },
    repairTypeCode: {
      type: String
    }
  },
  data() {
    this.state = state;
    return {
      // 表单
      list: this.createList(),
      columns: this.createColumns(),
      dataSource: [],
      isShowAddWxll: false,
      selectRows: [],
      tabaleList: []
      // isDels: []
    };
  },
  mounted() {
    // this.list.find(x => x.fieldName == 'receiver').initialValue = state.dict_llr[0].value; // 领料人默认第一个
    this.createBaseTable();
    this.getDealerUser();
    this.queryMaintainPicking();
    // this.setDefaultLLR(); // 设置默认领料人
  },
  methods: {
    createList() {
      return [
        {
          type: 'SELECT',
          label: '领料人',
          fieldName: 'receiver',
          initialValue: '',
          filterable: true,
          itemList: state.dict_llr,
          change: val => {
            this.changeReceiver(val);
          }
        }
      ];
    },
    createColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '配件代码',
          sorter: true,
          dataIndex: 'PART_NO',
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          sorter: true,
          dataIndex: 'PART_NAME',
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '数量',
          sorter: true,
          dataIndex: 'PART_QUANTITY',
          width: 100,
          editable: true,
          editRequired: true,
          editType: 'number',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '单位',
          sorter: true,
          dataIndex: 'UNIT_NAME',
          disabled: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '单价',
          sorter: true,
          dataIndex: 'PART_SALES_PRICE',
          width: 100,
          editable: true,
          editRequired: true,
          editType: 'number',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '不含税单价',
          sorter: true,
          dataIndex: 'PART_SALES_PRICE_NOTAX',
          precision: 2,
          filter: true,
          filterType: 'number',
          render: props => {
            props.row.PART_SALES_PRICE_NOTAX = (props.row.PART_SALES_PRICE / (1 + Number(this.tax))).toFixed(2);
            return <span>{props.row.PART_SALES_PRICE_NOTAX}</span>;
          }
        },
        {
          title: '含税金额',
          sorter: true,
          dataIndex: 'PART_SALES_AMOUNT',
          precision: 2,
          filter: true,
          filterType: 'number',
          render: props => {
            props.row.PART_SALES_AMOUNT = (props.row.PART_SALES_PRICE * props.row.PART_QUANTITY).toFixed(2);
            return <span>{props.row.PART_SALES_AMOUNT}</span>;
          }
        },
        {
          title: '不含税金额',
          sorter: true,
          dataIndex: 'PART_SALES_AMOUNT_NOTAX',
          precision: 2,
          filter: true,
          filterType: 'number',
          render: props => {
            props.row.PART_SALES_AMOUNT_NOTAX = (props.row.PART_SALES_AMOUNT / (1 + Number(this.tax))).toFixed(2);
            return <span>{props.row.PART_SALES_AMOUNT_NOTAX}</span>;
          }
        },
        {
          title: '实收金额',
          sorter: true,
          dataIndex: 'REAL_AMOUNT',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '领料人',
          dataIndex: 'RECEIVER',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: [],
          filter: true,
          filterType: 'checkbox',
          filterItems: []
        },
        {
          title: '领料方式',
          sorter: true,
          dataIndex: 'PICK_TYPE',
          editable: false,
          editType: 'select',
          editItems: this.createDictList(8111),
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(8111)
        },
        {
          title: '渠道',
          sorter: true,
          dataIndex: 'BUY_REMARKS',
          filter: true,
          filterType: 'input'
        },
        {
          title: '收费区分',
          sorter: true,
          dataIndex: 'CHARGE_PARTITION_NAME',
          filter: true,
          filterType: 'input'
        },
        {
          title: '发料人',
          sorter: true,
          dataIndex: 'SENDER',
          editable: false,
          editType: 'select',
          editItems: [],
          filter: true,
          filterType: 'checkbox',
          filterItems: []
        },
        {
          title: '折扣率',
          width: 150,
          sorter: true,
          dataIndex: 'DISCOUNT',
          editable: false,
          defaultEditable: false,
          editType: 'number',
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '成本单价',
          sorter: true,
          dataIndex: 'PART_COST_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number',
          hidden: !isAuthorized('1313', '13131005')
        },
        {
          title: '服务顾问',
          dataIndex: 'SERVICE_ADVISOR',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: [],
          filter: true,
          filterType: 'checkbox',
          filterItems: []
        }
      ];
    },
    createBaseTable() {
      this.BaseTable = this.$refs.table.$refs.pageTable;
    },
    onRowSelectChange(val) {
      this.selectRows = val;
    },
    async syncDataChange(val) {
      for (const item of val) {
        if (this.repairTypeCode == '1' && !item.ITEM_ID) {
          item.CHARGE_PARTITION_CODE = 'S';
          item.CHARGE_PARTITION_NAME = '索赔类';
          item.PRICE_TYPE = 80501003;
          // 销售单价
          item.PART_SALES_PRICE = ((item.CLAIM_PRICE || 0) * item.PRICE_RATE).toFixed(2);
          // // 含税金额
          // obj.PART_SALES_AMOUNT = (obj.PART_SALES_PRICE * obj.PART_QUANTITY).toFixed(2);
          // // 不含税单价
          // obj.PART_SALES_PRICE_NOTAX = (obj.PART_SALES_PRICE / (1 + this.tax * 1)).toFixed(2);
          // // 不含税金额
          // obj.PART_SALES_AMOUNT_NOTAX = (obj.PART_SALES_PRICE_NOTAX * obj.PART_QUANTITY).toFixed(2);
          // 实收金额
          // item.REAL_AMOUNT = '0.00';
        }
        if (!this.isShow) {
          this.BaseTable.SET_CELL_DISABLED(item, 'PART_QUANTITY', true);
          this.BaseTable.SET_CELL_DISABLED(item, 'PART_SALES_PRICE', true);
          // this.BaseTable.SET_CELL_DISABLED(item, 'DISCOUNT', true);
        }
      }
      this.tabaleList = val;
    },
    changeReceiver(val) {
      if (this.dataSource.length > 0) {
        for (const item of this.dataSource) {
          if (!item.ITEM_ID) {
            item.RECEIVER = val;
          }
        }
      }
    },
    async queryMaintainPicking() {
      let params = {
        roNo: this.roNo,
        flag: 'A'
      };
      const res = await queryMaintainPicking(params);
      this.BaseTable.EXECUTE_INSERT(res.data);
    },
    // 获取人员数据接口
    async getDealerUser() {
      const res = await getDealerUser();
      let data = arrayObjDeWeight(res.data, 'userId');
      this.columns.find(x => x.dataIndex == 'SERVICE_ADVISOR').editItems = this.columns.find(x => x.dataIndex === 'SERVICE_ADVISOR').filterItems = this.columns.find(
        x => x.dataIndex == 'SENDER'
      ).editItems = this.columns.find(x => x.dataIndex === 'SENDER').filterItems = this.columns.find(x => x.dataIndex == 'RECEIVER').editItems = this.columns.find(
        x => x.dataIndex === 'RECEIVER'
      ).filterItems = data.map(x => ({
        text: x.employeeName,
        value: x.userId + ''
      }));
      let userList = data.map(x => ({
        text: x.employeeName,
        value: x.userId + ''
      }));
      this.list.find(x => x.fieldName === 'receiver').itemList = userList;
      userList.find(item => item.value == getUserId()) && (this.list.find(x => x.fieldName == 'receiver').initialValue = getUserId());
    },
    // 判断配件是否已存在
    partIsHave(partNo) {
      const isHave = this.dataSource.find(item => {
        return item['PART_NO'] == partNo;
      });
      return isHave;
    },
    /** 新增 */
    showAddWxll() {
      this.isShowAddWxll = true;
    },
    confirmAddWxll(row) {
      console.log('新增', row);
      // 判断是否存在
      const flag = this.dataSource.find(item => {
        const isHave = item['PART_NO'] === row['PART_NO'] && item['STORAGE_CODE'] === row['STORAGE_CODE'];
        const isRuZhang = item['IS_FINISHED'] == '10041001';
        return isHave && !isRuZhang;
      });
      if (flag) {
        console.log('配件已存在');
        this.$notify({
          title: '警告',
          message: '配件已存在',
          type: 'warning'
        });
        return;
      }
      row['ITEM_UPDATE_STATUS'] = 'A';
      if (row['LABOUR_CODE'] == null || row['LABOUR_CODE'] == '') {
        state.dict_sfqf.forEach(x => {
          if (x.value == 'Z') {
            row['CHARGE_PARTITION_NAME'] = x.text;
            row['CHARGE_PARTITION_CODE'] = x.value;
          }
        });
      } else {
        state.dict_sfqf.forEach(x => {
          if (x.value == row['CHARGE_PARTITION_CODE']) {
            row['CHARGE_PARTITION_NAME'] = x.text;
            row['CHARGE_PARTITION_CODE'] = x.value;
          }
        });
      }
      // 计算金额
      // 成本单价
      row.PART_COST_PRICE = Number(row.COST_PRICE);
      // 含税采购价
      row.hscgj = (row.PLAN_PRICE + row.PLAN_PRICE * this.tax).toFixed(2);
      // 含税采购金额
      row.hscgje = (row.hscgj * row.PART_QUANTITY).toFixed(2);
      // 加价率
      // row.ADD_RATE = (Number(row.PART_SALES_AMOUNT) / Number(row.PART_COST_AMOUNT)).toFixed(2);
      // console.log(`成本单价:${row.PART_COST_PRICE}  成本金额:${row.PART_COST_AMOUNT}  金额:${row.PART_SALES_AMOUNT}  加价率:${row.ADD_RATE}`);

      /** 处理数据 S */
      // 是否入账 默认否
      row.IS_FINISHED = 10041002;
      // 3C免办 默认否
      row.IS_CCC_PART = 10041002;
      // 折扣率 默认1
      row.IS_DISCOUNT = 10041002;
      row.DISCOUNT = 1;
      /** 处理数据 E */
      console.log(row, 'rowData');
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(row);
      this.$notify({
        title: '提示',
        message: '新增成功',
        type: 'success'
      });
    },
    addRow(row) {
      console.log('新增', row);
      // 判断是否存在
      row.PART_QUANTITY = 1;
      row.PART_SALES_PRICE = row.SALES_PRICE;
      row.CHARGE_PARTITION_NAME = '自费类';
      row.CHARGE_PARTITION_CODE = 'Z';
      row.PICK_TYPE = 81111001;
      // row.RECEIVER = this.list.find(x => x.fieldName == 'RECEIVER').initialValue ? this.list.find(x => x.fieldName == 'RECEIVER').initialValue : state.dict_llr.length ? state.dict_llr[0].value : '';
      row.IS_MAIN_PART = 10041002;
      row.PRICE_TYPE = 80501002;
      row.PRICE_RATE = 1;
      row.USEABLE_STOCK = row.USEABLE_QUANTITY;
      if (row.OEM_TAG == 10451002) {
        row.BUY_REMARKS = '原装';
      } else {
        row.BUY_REMARKS = '非原装';
      }
      const flag = this.dataSource.find(item => {
        const isHave = item['PART_NO'] === row['PART_NO'] && item['STORAGE_CODE'] === row['STORAGE_CODE'];
        const isRuZhang = item['IS_FINISHED'] == '10041001';
        return isHave && !isRuZhang;
      });
      if (flag) {
        console.log('配件已存在');
        this.$notify({
          title: '警告',
          message: '配件已存在',
          type: 'warning'
        });
        return;
      }
      row['ITEM_UPDATE_STATUS'] = 'A';
      if (row['LABOUR_CODE'] == null || row['LABOUR_CODE'] == '') {
        state.dict_sfqf.forEach(x => {
          if (x.value == 'Z') {
            row['CHARGE_PARTITION_NAME'] = x.text;
            row['CHARGE_PARTITION_CODE'] = x.value;
          }
        });
      } else {
        state.dict_sfqf.forEach(x => {
          if (x.value == row['CHARGE_PARTITION_CODE']) {
            row['CHARGE_PARTITION_NAME'] = x.text;
            row['CHARGE_PARTITION_CODE'] = x.value;
          }
        });
      }
      // 计算金额
      // 成本单价
      row.PART_COST_PRICE = Number(row.COST_PRICE);
      // 含税采购价
      row.hscgj = (row.PLAN_PRICE + row.PLAN_PRICE * this.tax).toFixed(2);
      // 含税采购金额
      row.hscgje = (row.hscgj * row.PART_QUANTITY).toFixed(2);
      // 加价率
      // row.ADD_RATE = (Number(row.PART_SALES_AMOUNT) / Number(row.PART_COST_AMOUNT)).toFixed(2);
      // console.log(`成本单价:${row.PART_COST_PRICE}  成本金额:${row.PART_COST_AMOUNT}  金额:${row.PART_SALES_AMOUNT}  加价率:${row.ADD_RATE}`);

      /** 处理数据 S */
      // 是否入账 默认否
      row.IS_FINISHED = 10041002;
      // 3C免办 默认否
      row.IS_CCC_PART = 10041002;
      // 折扣率 默认1
      row.IS_DISCOUNT = 10041002;
      row.DISCOUNT = 1;
      row.RECEIVER = this.list.find(x => x.fieldName == 'receiver').initialValue;
      /** 处理数据 E */
      console.log(row, 'rowData');
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(row);
      this.$notify({
        title: '提示',
        message: '新增成功',
        type: 'success'
      });
    },
    // 删除选中行
    deleteHandle() {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let isDels = [];
          let dels = [];
          for (const item of this.selectRows) {
            if (item.ITEM_ID) {
              // this.isDels.push(item.ITEM_ID);
              isDels.push(item.ITEM_ID);
            } else {
              dels.push(item);
            }
          }
          if (isDels.length > 0) {
            let res = await delFrontPartInfo(isDels.join(','), this.roNo);
            if (res.resultCode == 200) {
              this.$notify.success({ title: '提示信息', message: '删除成功' });
              this.dataSource = [];
              this.queryMaintainPicking();
            }
          } else {
            this.BaseTable.EXECUTE_DELETE(this.dels);
            this.$notify.success({ title: '提示信息', message: '删除成功' });
          }
        })
        .catch(() => {});
    },
    async saveDialog() {
      console.log(this.BaseTable.GET_REQUIRED_ERROR());
      if (this.BaseTable.GET_REQUIRED_ERROR() == null) {
        if (!this.list.find(x => x.fieldName == 'receiver').initialValue) {
          return this.$notify.error({ title: '提示信息', message: '请选择领料人' });
        }
        let params = {
          roNo: this.roNo
          // isDels: this.isDels
        };
        params.maintainPickingTbl = this.dataSource.map(item => {
          const row = util.camelCaseObject(item);
          // const dict = this.columns.find(x=>x.dataIndex === 'LABOUR_CODE').editItems.find(x => x.value == row['labourCode']);
          if (row.labourCode) {
            // 开启配件关联维修项目开关后，前台需要向后台传配件所关联的维修项目的labourItemId
            const labourItem = state.dict_xlxm.find(x => x.value == row.labourCode);
            if (labourItem) {
              row.labourItemId = labourItem.labourItemId;
            }
          }
          // row.labourItemId = dict.value2;
          return row;
        });
        const res = await saveRepairFront(params);
        if (res.resultCode == 200) {
          this.$notify.success({ title: '提示信息', message: '保存成功' });
          this.dataSource = [];
          this.queryMaintainPicking();
        }
      }
    },
    // 设置默认领料人
    async setDefaultLLR() {
      let llrRes = await getLingLiaoRenSelect();
      let lightData = arrayObjDeWeight(llrRes.data, 'userId');
      let llrDict = lightData.map(x => ({ text: x['employeeName'], value: x['userId'] }));
      this.list.find(x => x.fieldName == 'receiver').itemList = llrDict;
      llrDict.find(item => item.value == getUserId()) && (this.list.find(x => x.fieldName == 'receiver').initialValue = getUserId());
    }
  }
};
</script>

<style scoped>
.btn-wrap {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 60px;
}
</style>
